package com.las.bot.cmd.other;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.las.bot.common.Constant;
import com.utils.IdUtil;
import com.utils.ThreadUtil;
import com.utils.legao.Mode;
import com.utils.legao.MosaicMaker;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseCommand;
import com.las.utils.DownImgUtil;
import com.las.utils.StrUtils;
import com.las.utils.mirai.CmdUtil;
import com.las.utils.mirai.MiRaiUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

//@BotCmd(funName = "乐高马赛克")
//@Scope("prototype")
public class LeGaoCmd extends BaseCommand {

    private static Logger logger = LoggerFactory.getLogger(LeGaoCmd.class);

    private AtomicInteger count = new AtomicInteger(1);

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    public LeGaoCmd() {
        super("LG", "", "", "乐高图");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        if (type != com.las.common.Constant.MESSAGE_TYPE_GROUP) {
            return;
        }
        if (args.size() == 1) {
            String number = args.get(0);
            if (StrUtils.isNumeric(number)) {
                CmdUtil.sendMessage("色乐高才支持系数，当前默认设置为300", userId, id, type);
            }
        }
        List<JSONObject> groupUserList = MiRaiUtil.getInstance().getGroupUsers(id);
        if (CollectionUtil.isNotEmpty(groupUserList)) {
            initGroupImg(id, groupUserList);
            String path = System.getProperty("user.dir");
            for (int i = 0; i < 20; i++) {
                Thread.sleep(500);
                String filePath = path + File.separator + id;
                String[] imgList = new File(filePath).list();
                if (null != imgList) {
                    logger.info("检测群图片数量:" + imgList.length + " -->" + count.get());
                    if (count.get() == imgList.length + 1) {
                        logger.info("群头像收齐完毕！");
                        break;
                    }
                }
            }
            // 新人进群，有时候头像不一定凑齐，直接触发生成乐高图即可
            String msg = "正在生成乐高图ing...请耐心等会~";
            CmdUtil.sendMessage(msg, userId, id, type);
            executor.execute(() -> createLg(userId, id, type, path));
        }
    }

    private void createLg(Long userId, Long id, Integer type, String path) {
        // 实现准备好空集合
        ArrayList<String> urls = new ArrayList<>();
        // 下一步生成马赛克图
        String sourcePath = path + File.separator + id;
        String targetPath = path + File.separator + id + "_target";
        File tf = new File(targetPath);
        if (!tf.exists()) {
            tf.mkdirs();
        }
        String targetFile = StrUtils.uuid() + Constant.IMG_PNG;
        URL url = LeGaoCmd.class.getClassLoader().getResource("static/img");
        assert url != null;
        logger.info("读取源路径：" + url.getPath());
        File[] arr = new File(url.getPath()).listFiles();
        if (arr != null && arr.length > 0) {
            int index = new Random().nextInt(arr.length);
            File sourceFile = arr[index];
            logger.info("读取源文件：" + sourceFile.getAbsolutePath());
            MosaicMaker mosaicMaker = new MosaicMaker(sourcePath, sourceFile.getAbsolutePath(), targetPath + File.separator + targetFile, 300);
            //mosaicMaker.setUseTree(true);
            mosaicMaker.setMode(Mode.RGB);
            File file = new File(targetPath + File.separator + targetFile);
            try {
                mosaicMaker.make();
                String objectName = IdUtil.nextId() + Constant.BUCKET_PNG;
                // 下一步将目标图上传到阿里云
                String endpoint = Constant.HTTPS + Constant.OSS;
                String accessKeyId = Constant.BUCKET_ID;
                String accessKeySecret = Constant.BUCKET_KEY;
                String bucketName = Constant.BUCKET_NAME;
                // 上传到阿里云OSS
                OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                ossClient.putObject(bucketName, objectName, file);
                ossClient.shutdown();
                String imgUrl = Constant.HTTPS + Constant.BUCKET_NAME + "." + Constant.OSS + objectName;
                logger.info("上传到阿里云原图：" + imgUrl);
                urls.add(imgUrl);
                if (CollectionUtil.isNotEmpty(urls)) {
                    CmdUtil.sendImgMessage(urls, userId, id, type);
                }


            } catch (Exception e) {
                logger.error("生成乐高马赛克图失败：" + e.getMessage());
                CmdUtil.sendMessage("生成图失败...请稍后再试...", userId, id, type);
            } finally {
                // 上传成功后需要删除本地图
                if (file.exists()) {
                    file.delete();
                }
            }
        }
    }

    private void initGroupImg(Long id, List<JSONObject> groupUserList) {
        // 开启线程，将群水友的所有头像保存到本地
        groupUserList.forEach(obj -> executor.execute(() -> {
            String qq = obj.getString("id");
            String imgUrl = "http://q1.qlogo.cn/g?b=qq&nk=" + qq + "&s=100";
            String path = System.getProperty("user.dir") + File.separator + id;
            String fileUrl = DownImgUtil.downLoadFromUrl(imgUrl, qq + Constant.IMG_PNG, path);
            logger.info(count.get() + " - 保存群水友头像到项目本地路径：" + fileUrl);
            count.getAndIncrement();
        }));
    }

}
